package com.shrw.duke.bluetoothheartrate.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shrw.duke.bluetoothheartrate.R;
import com.shrw.duke.bluetoothheartrate.entity.RateEntity;
import com.shrw.duke.bluetoothheartrate.entity.StateEntity;
import com.shrw.duke.bluetoothheartrate.utils.Convert;
import com.shrw.duke.bluetoothheartrate.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import io.netopen.hotbitmapgg.view.NewCreditSesameView;

public class RateActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int SECONDS = 1000;

    public static final String _CRNO_1 = "C7";
    public static final String _CRNO_2 = "1400";
    public static final String _LABEL_TYPE = "F0";
    public static final String LABEL_DATA = "LABEL_DATA";
    private static final String TAG = "RateActivity";

    //    private RingView mRingView;
    private ImageView mImgBtnAdd, mImgFirst;
    private RelativeLayout mRelative;
    private TextView mTitle;
    private TextView mTvBleStatus;
//    private TextView mTvRate;


    private SPUtils mSPUtils;
    private String mName;
    private String mAddress;
    private boolean mFirst;
    private boolean permission;

    private List<RateEntity> rateEntityList = new ArrayList<>();
    private BluetoothAdapter bluetoothAdapter = null;
    private Handler mHandler = new Handler();
    private NewCreditSesameView newCreditSesameView;
    private boolean isScan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);
//        initToolsBar();
        initView();
        initAction();
        initPermissions();
    }


    @Override
    protected void onStart() {
        super.onStart();
        resetNameAddress();

        if (mFirst) {
            mImgFirst.setVisibility(View.VISIBLE);
            mRelative.setVisibility(View.GONE);
        } else {
            mImgFirst.setVisibility(View.GONE);
            mRelative.setVisibility(View.VISIBLE);
            if (permission) {
//                mRingView.startAnim();
                bluetooth();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                //非授权列表
                List<String> unAuthpermissionList = new ArrayList<>();
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        unAuthpermissionList.add(permissions[i]);
                    }
                }

                if (unAuthpermissionList.size() > 0) {
                    //如果拒绝授予权限,且勾选了再也不提醒
                    if (!shouldShowRequestPermissionRationale(permissions[0])) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("说明")
                                .setMessage("需要使用" + Manifest.permission.ACCESS_COARSE_LOCATION + "权限，才能调用手机的蓝牙功能")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        showTipGoSetting();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                })
                                .create()
                                .show();
                    } else {
                        showTipGoSetting();
                    }
                } else {
                    permission = true;
                    bluetooth();
                }

                break;
        }
    }

    /**
     * 用于在用户勾选“不再提示”并且拒绝时，再次提示用户
     */
    private void showTipGoSetting() {
        new AlertDialog.Builder(this)
                .setTitle(Manifest.permission.ACCESS_COARSE_LOCATION + "权限不可用")
                .setMessage("请在-应用设置-权限-中，允许APP使用" + Manifest.permission.ACCESS_COARSE_LOCATION + "权限来测试")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).setCancelable(false).show();

    }


    /**
     * 打开Setting
     */
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

    private void initPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String[] s = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION};
            for (String s1 : s) {
                if (!hasPermission(s1)) {
                    requestPermissions(s, 1);
                } else {
                    permission = true;
//                    bluetooth();
                }
            }

        } else {
            permission = true;
//            bluetooth();
        }
    }

    public boolean hasPermission(String permission) {
        int perm = ContextCompat.checkSelfPermission(this, permission);
        return perm == PackageManager.PERMISSION_GRANTED;
    }

    private void resetNameAddress() {
        mName = mSPUtils.getString(AddPeopleActivity.NAME, "");
        mAddress = mSPUtils.getString(AddPeopleActivity.ADDRESS, "");
        mFirst = mSPUtils.getBoolean(AddPeopleActivity.FIRST, true);
        if (mFirst) {
            mTitle.setText("心跳");
        } else {
            mTitle.setText(mName);
        }
    }

    private void initAction() {
        mImgBtnAdd.setOnClickListener(this);
//        mTvRate.setOnClickListener(this);
        mImgFirst.setOnClickListener(this);
        newCreditSesameView.setOnClickListener(this);
    }

    private void initView() {

        newCreditSesameView = (NewCreditSesameView) findViewById(R.id.sesame_view);

        mSPUtils = SPUtils.getInstance(this, "people");
//        mRingView = (RingView) findViewById(R.id.rate_ring_view_img);
        mImgBtnAdd = (ImageView) findViewById(R.id.toolbar_menu);
        mImgFirst = (ImageView) findViewById(R.id.rate_img_null);
        mRelative = (RelativeLayout) findViewById(R.id.rate_normal_relative);
        mTitle = (TextView) findViewById(R.id.toolbar_title);
        mTvBleStatus = (TextView) findViewById(R.id.tv_ble_status);
        mTvBleStatus.setText("连接中");
//        mTvRate = (TextView) findViewById(R.id.rate_img);

//        mTitle.setText("");
        mImgBtnAdd.setImageResource(R.drawable.ic_add_circle_black_24dp);
    }

    private void initToolsBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_menu:
            case R.id.rate_img_null:
                startActivity(new Intent(this, AddPeopleActivity.class));
                break;
            case R.id.sesame_view:
                if (rateEntityList.size() == 0) {
                    Toast.makeText(RateActivity.this, "稍等片刻", Toast.LENGTH_SHORT).show();
                    break;
                }
                Bundle bundle = new Bundle();
                bundle.putParcelable(LABEL_DATA, rateEntityList.get(rateEntityList.size() - 1));
                Intent intent = new Intent(RateActivity.this, RateDataActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                break;

//            case R.id.rate_img:
//                if (rateEntityList.size() == 0) {
//                    Toast.makeText(RateActivity.this, "稍等片刻", Toast.LENGTH_SHORT).show();
//                    break;
//                }
//                Bundle bundle = new Bundle();
//                bundle.putParcelable(LABEL_DATA, rateEntityList.get(rateEntityList.size() - 1));
//                Intent intent = new Intent(RateActivity.this, RateDataActivity.class);
//                intent.putExtras(bundle);
//                startActivity(intent);
//                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopBluetooth();
    }


    private void bluetooth() {
        BluetoothManager bluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
        }
//        newCreditSesameView.setSesameValues(63);
        if (!isScan){
            isScan = bluetoothAdapter.startLeScan(mLeScan);
            mHandler.postDelayed(scanFailRunnable,SECONDS*10);
        }

//        mRingView.startAnim();
    }

    private void stopBluetooth() {
        if (bluetoothAdapter != null) {
            bluetoothAdapter.stopLeScan(mLeScan);
            isScan = false;
        }
    }

    BluetoothAdapter.LeScanCallback mLeScan = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            String address = device.getAddress().replaceAll(":", "").toUpperCase();
            Log.d("LLLL", Thread.currentThread().getName());
            if (address.equals(mAddress.toUpperCase())) {

                String[] recordArray = Convert.toHexStringArray(scanRecord, scanRecord.length);

                String CRNO_1 = recordArray[5];
                String label_type = recordArray[7];
                StringBuilder CRNO_2 = new StringBuilder();
                CRNO_2.append(recordArray[16]);
                CRNO_2.append(recordArray[17]);

                if (_CRNO_1.equals(CRNO_1)
                        && _CRNO_2.equals(CRNO_2.toString())
                        && _LABEL_TYPE.equals(label_type)) {
                    if ( !"已连接".equals(mTvBleStatus.getText().toString())){
                        mTvBleStatus.setText("已连接");
                    }
                    StringBuilder record = Convert.toHexString(scanRecord, scanRecord.length);
                    Log.w(TAG, "onLeScan: "+device.getAddress());

                    mHandler.removeCallbacksAndMessages(null);
                    String label = record.substring(18, 29);
//                        String rateStr = record.substring(38,61);
                    char[] stateArray = Convert.hexString2binaryString(recordArray[18]).toCharArray();
                    RateEntity rateEntity = new RateEntity();
                    rateEntity.setName(mName);
                    rateEntity.setAddress(label);
                    rateEntity.setRecord(record.toString());
                    rateEntity.setRssi(rssi);
                    rateEntity.setStateEntity(new StateEntity(stateArray[0], stateArray[1], stateArray[2], stateArray[3],
                            stateArray[4], stateArray[5], stateArray[6], stateArray[7]));
                    rateEntity.setRate(recordArray[20]);
                    rateEntity.setVolt(recordArray[19]);
                    rateEntity.setLf_Times(recordArray[21]);
                    rateEntity.setNrf_Times(recordArray[22]);
                    rateEntity.setAID_STR1_ActID(recordArray[23] + recordArray[24]);
                    rateEntity.setAID_STR1_Rssi(recordArray[25]);
                    rateEntity.setAID_STR2_ActID(recordArray[26] + recordArray[27]);
                    rateEntity.setAID_STR2_Rssi(recordArray[28] + recordArray[27]);
                    rateEntity.setAID_STR3_ActID(recordArray[29] + recordArray[30]);
                    rateEntity.setMeasoreTime(newCreditSesameView.getCurrentTime());
                    int rate = Integer.parseInt(rateEntity.getRate(), 16);
                    newCreditSesameView.setSesameValues(Math.abs(rate));

//                    mTvRate.setText(rate + "");
//                    mRingView.setmAnimAngle(29);
                    rateEntityList.add(rateEntity);
                    mHandler.postDelayed(rateRunnable,SECONDS*6);
                    Log.w(TAG, "onLeScan: end");

                } else {
//                    Toast.makeText(RateActivity.this, "绑定错误", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    Runnable rateRunnable = new Runnable() {
        @Override
        public void run() {
//            newCreditSesameView.setSesameValues(0f);
            mTvBleStatus.setText("通信中断");
            Toast.makeText(RateActivity.this, "通信中断", Toast.LENGTH_SHORT).show();
            mHandler.postDelayed(scanFailRunnable,SECONDS*10);
        }
    };

    Runnable scanFailRunnable = new Runnable() {
        @Override
        public void run() {
            mTvBleStatus.setText("不在搜索范围");
        }
    };
}
